package com.bbva.kyfb.kyfbdto.abstracts;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import com.bbva.kyfb.kyfbdaofo.interfaces.Dao;

@SuppressWarnings("rawtypes")
public abstract class DaoAbstract<E, P> implements Dao<E, P> {

	protected EntityManager entityManager;
	
	protected abstract void setEntityManager(EntityManager entityManager);

	@SuppressWarnings("unchecked")
	public E select(P entityPK) {
		E entity = (E) entityManager.find(clase, entityPK);
		return entity;
	}

	public void insert(E entity) {
		entityManager.persist(entity);
	}

	public E update(E entity) {
		return entityManager.merge(entity);
	}

	public void delete(E entity) {
		if (!entityManager.contains(entity)) {
			// entity = select(entity);
		}
		entityManager.remove(entity);
	}

	public void flush() {
		entityManager.flush();
	}

	private Class clase;

	public DaoAbstract(Class aClass) {
		clase = aClass;
	}

	@SuppressWarnings("unchecked")
	public List<E> selectList() {
		TypedQuery<E> typedQuery = entityManager
				.createQuery(
						"Select e From table e".replace("table",
								clase.getSimpleName()), clase);
		List<E> entityList = typedQuery.getResultList();
		return entityList;
	}
}